package com.bjqh.edu.UI.Activity.StudentPersonal;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bjqh.edu.Base.AppConstants;
import com.bjqh.edu.Bean.Order;
import com.bjqh.edu.MainActivity;
import com.bjqh.edu.R;
import com.bjqh.edu.UI.Activity.Login.LoginActivity;
import com.bjqh.edu.UI.Utils.AuthResult;
import com.bjqh.edu.UI.Utils.PayDemoActivity;
import com.bjqh.edu.UI.Utils.PayResult;
import com.bjqh.edu.wxapi.Constants;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class PaymentActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_top_tilte)
    RelativeLayout rlTopTilte;
    @BindView(R.id.tv_pp)
    TextView tvPp;
    @BindView(R.id.btn_login)
    Button btnzf;
    String aipay;
    @BindView(R.id.tv_or_num)
    TextView tvOrNum;
    @BindView(R.id.wx)
    RadioButton wx;
    @BindView(R.id.zfb)
    RadioButton zfb;
    @BindView(R.id.zf)
    RadioGroup zf;
    @BindView(R.id.wx_ll)
    LinearLayout wxLl;
    @BindView(R.id.zfb_ll)
    LinearLayout zfbLl;
    private Order.OrderBean orderBean;
    IWXAPI api;
    Order.WechatPayBean wechatPayBean;
    private static final int SDK_PAY_FLAG = 1;

    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_payment);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(getApplication(), Constants.APP_ID);
        api.registerApp(Constants.APP_ID);
        String coursename = getIntent().getExtras().getString("coursename");
        String price = getIntent().getExtras().getString("price");
        String coursedes = getIntent().getExtras().getString("coursedes");
        String cid = getIntent().getExtras().getString("cid");
        tvPp.setText("￥" + price);
        btnzf.setText("确认支付￥" + price);
        //获取手机型号
        String model = Build.MODEL;
        if (getIntent().getExtras().getString("ordernum") != null) {
            OkGo.post(AppConstants.BASE_URL + "/order/addOrder.shtml")
                    .tag(this)
                    .cacheKey("cacheKey")
                    .cacheMode(CacheMode.DEFAULT)
                    .params("ordernum", getIntent().getExtras().getString("ordernum"))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            //  Toast.makeText(PaymentActivity.this, "请求成功" + s, Toast.LENGTH_SHORT).show();
                            Log.e("22222", s);
                            Gson gson = new Gson();
                            Order order = gson.fromJson(s, Order.class);
                            if(order.getMsg()!=null){
                                if(order.getMsg().equals("timeout")){

                                    AppConstants.gotoLogin(PaymentActivity.this);
                                }
                                else {
                                    aipay = order.getAiPay();
                                    orderBean = order.getOrder();
                                    wechatPayBean = order.getWechatPay();
                                    tvOrNum.setText("订单编号：" + orderBean.getOrdernum());
                                }
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            Toast.makeText(PaymentActivity.this, "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                        }
                    });

        } else {
            OkGo.post(AppConstants.BASE_URL + "/order/addOrder.shtml")
                    .tag(this)
                    .cacheKey("cacheKey")
                    .cacheMode(CacheMode.DEFAULT)
                    .params("coursename", coursename)
                    .params("price", price)
                    .params("coursedes", coursedes)
                    .params("cid", cid)
                    .params("deviceinfor", model)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            //  Toast.makeText(PaymentActivity.this, "请求成功" + s, Toast.LENGTH_SHORT).show();
                            Log.e("1111111", s);
                            Gson gson = new Gson();
                            Order order = gson.fromJson(s, Order.class);
                            if(order.getMsg()!=null){
                                if(order.getMsg().equals("timeout")){

                                    AppConstants.gotoLogin(PaymentActivity.this);
                                }
                                else {
                                    aipay = order.getAiPay();
                                    orderBean = order.getOrder();
                                    wechatPayBean = order.getWechatPay();
                                    tvOrNum.setText("订单编号：" + orderBean.getOrdernum());
                                }
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            Toast.makeText(PaymentActivity.this, "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
        wxLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wx.setChecked(true);
            }
        });
        zfbLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zfb.setChecked(true);
            }

        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvTitle.setText("支付");
        btnzf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (wx.isChecked()) {
                    PayReq req = new PayReq();
                    req.prepayId = wechatPayBean.getPrepay_id();
                    req.appId = wechatPayBean.getAppid();
                    req.partnerId = wechatPayBean.getMch_id();
                    req.packageValue = "Sign=WXPay";
                    req.nonceStr = wechatPayBean.getNonce_str();
                    long ut = orderBean.getTime() / 1000;
                    req.timeStamp = ut + "";
                    req.sign = wechatPayBean.getSign();
                    req.extData = "app data";

                    boolean flag = api.sendReq(req);
                    Log.i("111111111", flag + "");
                    finish();

                 /*   try {
                       String A="appid="+wechatPayBean.getAppid()+"&partnerid="+wechatPayBean.getMch_id()+"&prepayid="+wechatPayBean.getPrepay_id()+"&package=Sign=WXPay"+"&noncestr="+wechatPayBean.getNonce_str()+"&timestamp="+String.valueOf(orderBean.getTime()/1000)+"&key=7sla8ob5rez0zhukPYBn4Kkj2pfvvyMq";
                        PayReq req = new PayReq();
                        req.appId = wechatPayBean.getAppid();  //
                        req.partnerId = wechatPayBean.getMch_id();
                        req.prepayId = wechatPayBean.getPrepay_id();
                        req.nonceStr = wechatPayBean.getNonce_str();
                        req.timeStamp =String.valueOf(orderBean.getTime()/1000);
                        req.packageValue = "Sign=WXPay";
                       // req.sign = AppConstants.md5(A).toUpperCase();
                        req.sign=wechatPayBean.getSign();
                        //  req.extData			= "app data"; // optional
                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        api.registerApp(Constants.APP_ID);
                        api.sendReq(req);
                    } catch (Exception e) {
                        Log.e("PAY_GET", "异常：" + e.getMessage());
                        Toast.makeText(PaymentActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }*/
                } else {
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(PaymentActivity.this);
                            Map<String, String> result   = alipay.payV2(aipay, true);
                            Log.i("msp", result.toString());

                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();

                }

            }
        });


    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PaymentActivity.this, "小主，支付成功啦~~", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(PaymentActivity.this,OrderActivity.class));
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PaymentActivity.this, "小主，支付失败啦，您可在我的订单—待支付界面重新支付", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

}
